/**
 * @class Cart
 * @extends Ext.Controller
 * The Cart controller
 */

Ext.regController('Cart', {
	store: RefApp.stores.cartStore,				// reference to the cart store
	formStore: RefApp.stores.orderFormStore,	// reference to the order form store
	
	/*
	* Summary:		Initialization controller 
	* 				(note: cannot use init name - it's controller used before launch application function) 
	* Parameters:	none
	*/
	
	initController : function(){
		this.clearCart();			// clear cart
		this.refreshCart();			// cart tab initialization
	},
	
	/*
	* Summary:		Function shows menu tab. 
	* Parameters:	none
	*/
	
	showMenu : function(){
		Ext.dispatch({
			controller: 'Menu',
			action: 'showMenu'	
		});
	},
	
	/*
	* Summary:		Function shows form in cart tab. 
	* Parameters:	none
	*/
	
	showForm : function(){
		
		if(this.store.data.length == 0)
		{
			Ext.History.add(RefApp.defaultUrl);
			this.showMenu();
			return ;
		}
		
		if(RefApp.views.viewport.getActiveItem().id != 'cart')
		{
			Ext.dispatch({
		  		controller: 'Menu',
		  		action: 'showCart'
			});
		}
		
		var model;
		
		if(this.formStore.data.length > 0){				// load data from the store
			model = this.formStore.getAt(0);			// load model instance
		}
		else{											// create new model
			model = new RefApp.models.OrderForm();		// new model instance
		}
		RefApp.views.cartForm.load(model);				// load model to the form
		RefApp.views.cartCard.changePanel('cartForm');	// change tab
	},
	
	/*
	* Summary:		Function shows list in cart tab. 
	* Parameters:	none
	*/
	
	showCartList : function(){
		RefApp.views.cartCard.changePanel('cartList');
	},
	
	
	/*
	* Summary:		Function delete item from the store
	* Parameters:	item: item to delete
	*/
	deleteItem : function(p){
		this.store.removeAt(p.item);
		this.store.sync();
		this.refreshCart();
	},
	
	/*
	* Summary:		Function clears Cart by deleting every record from the store and reset badgeText in cart icon
	* Parameters:	none
	*/
	
	clearCart : function(){
		// clear store
		for(var i = this.store.data.length -1 ; i >= 0;  i--){
			this.store.removeAt(i);							// remove record
		}
		
		this.store.sync();
		this.refreshCart();
	},

	/*
	* Summary:		Add item to the cart
	* Parameters:	item: item to add | size: size of the item
	*/
	
	addItem : function(p){
		p.item.size = p.size;					// set size of the item
		this.store.add(p.item);					// add item to the store
		this.store.sync();
		this.refreshCart();						// refresh Cart Tab
	},
	
	
	/*
	* Summary:		Function calculates overall cost of items in cart
	* Parameters:	none
	* Return: 		cost (type: float)
	*/
	
	totalCost : function(){
		var cost = 0,
			leadingZeros = 2,											// leading zeros to approximate cost			
			factor = Math.pow(10, leadingZeros);						// 10 to the power of leading zeros
		
		for(var i =0; i < this.store.data.length; i++){					// for each item
			cost += parseFloat(this.store.data.items[i].data.price);	// add cost
		}
		
		cost = Math.round(cost*factor)/factor;							// round cost
		
		return cost;
	},
	
	/*
	* Summary:		Function refreshes cart toolbar and disable/enable order-button
	* Parameters:	none
	*/
	
	refreshCart : function(){
		var toolbar = RefApp.views.viewport.down('#cartToolbar'), 	// reference to the cart-toolbar
			button = RefApp.views.viewport.down('#orderButton');	// reference to the cart-order-button
		
		toolbar.setTitle('Koszyk ('+this.totalCost()+' '
				+RefApp.Config.currency+')');						// set toolbar title
		button.setDisabled(!this.store.data.length);				// if store is empty disable order-button

		Ext.dispatch({												// refresh badge text on cart icon
	  		controller: 'Menu',
	  		action: 'refreshBadge',
		});
	},
	
	/*
	* Summary:		Reset all form fields
	* Parameters:	data: all data from form | record: record model | form: RefApp.views.CartForm component
	*/
	
	formReset : function(p){
		p.form.fields.each(function(field) {						// hide all error fields
			p.form.resetField(field);
		}, p.form);

		this.formStore.getProxy().clear();							// clear localstorage
		this.formStore.load();										// workaround - load data from localstore (which is empty)
		p.form.load(new RefApp.models.OrderForm());	// new model instance
	},
	
	/*
	* Summary:		If all fields are valid - submit form, clear cart and form and show menu, otherwise - show error messages
	* Parameters:	data: all data from form | record: record model | form: RefApp.views.CartForm component
	*/
	
	formSubmit : function(p){
		
		p.record.set(p.data);						// set record data basing on form data
		var errors = p.record.validate();			// validate form basing on OrderForm model validate property
		
		if(errors.isValid())						// if all fields are correct
		{
			p.form.afterOrder();					// alert message
			
			// data save - TO DO
			console.log(p.data);
			console.log(this.store);

			this.clearCart();						// clear cart 		
			this.formReset({form: p.form});			// clear form
			this.formStore.create(p.data);			// save form data to localstorage
			this.formStore.sync();					// synchronize localstorage
			this.showMenu();						// go to menu
		}
		else										// if there are invalid fields
		{
			p.form.showErrors(errors);				// show errors
		}
		
	}
	
});